import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class PublicHeaderInterceptor extends Interceptor {
  final ValueGetter userIdGetter;
  final ValueGetter tokenGetter;

  PublicHeaderInterceptor({
    this.tokenGetter,
    this.userIdGetter,
  });

  @override
  Future onRequest(RequestOptions options) async {
    Map<String, dynamic> header;
    if (options.method == 'GET') {
      //只针对query 签名
      header = _getSignHeaders(query: options.uri.queryParameters);
    } else {
      //只针对body签名
      var data = options.data;
      if (data is Map) {
        header = _getSignHeaders(body: data);
      } else if (data is String) {
        header = _getSignHeaders(body: json.decode(data));
      } else {
        header = _getSignHeaders(body: null);
      }
    }

    if (options.headers != null && options.headers.length > 0) {
      var map = Map<String, dynamic>();
      map.addAll(options.headers);
      if (header != null) map.addAll(header);
      header = map;
    }
    return options.merge(
      headers: header,
    );
  }

  //接收String 和 Map 两种类型
  Map<String, dynamic> _getSignHeaders({Map body, Map query}) {
    final userId = userIdGetter?.call() ?? '';
    final token = tokenGetter?.call() ?? '';
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    return {
      'X-Req-Date': currentTime,
      'Authorization': token,
      'X-Req-UserId': userId,
      'time': currentTime,
    };
  }
}
